<?php
/**
 * Created by PhpStorm.
 * User: zyw
 * Date: 2018-02-28
 * Time: 14:31
 */

class PostModel extends MY_Model{
    public $table = 't_post';
    public function __construct(){
        parent::__construct();
    }

    /**
     * 取帖子列表
     * name: getPostList
     * @param int $status 状态0取可以审核的数据   其它数值取相对应的数据
     * @param int $page
     * @param int $pagesize
     * @return mixed
     * @Author:taiyang
     */
    public function getPostList($status = 0,$page=1,$pagesize=10){
        //N分钟内的数据不取
        $n=10;
        $time=date("Y-m-d H:i:s",time()-60*$n);
        $sql="select * from ".$this->table." where 1 ";

        if($status == 1 && $status !== "all"){//待审核
            $sql.=" and is_audit = 0 or (is_audit = 2  and `update_time` <= '".$time."') ";
            $pagesize=5;
        }elseif($status == 2 && $status !== "all"){//已审核
            $sql.=" and is_audit = 1";
        }
        $sql.=" order by `add_time` asc ";
        $index = $page - 1 < 0 ? 0 : ($page - 1) * $pagesize;
        $sql.=" limit ".$index.",".$pagesize."";
        $list=$this->query_sql_list($sql);
        //为取出的内容更改状态，其它人不可再取出
        if($status == 1 && $status !== "all"){
            foreach($list as $k=> $post){
                $this->update_data(array('is_audit'=>2,'update_time'=>date("Y-m-d H:i:s",time())),array('id'=>$post['id']));
            }
        }
        return $list;
    }

    public function getPostListNum($status){
        $time=date("Y-m-d H:i:s",time()-10);
        $sql="select count(*)as num from ".$this->table." where 1 ";
        if($status == 1 && $status !== "all"){//待审核
            $sql.=" and is_audit = 0 or (is_audit = 2  and `update_time` <= '".$time."') ";
        }elseif($status == 2 && $status !== "all"){//已审核
            $sql.=" and is_audit = 1";
        }
        return $this->query_sql_count($sql);
    }

    /**
     * 帖子具体数据显示
     * name: get_post_data
     * @param $data
     * @return mixed
     * @throws Exception
     * @Author:taiyang
     */
    public function get_post_data($data){
        //查询音频
        if(!empty($data['audio_id'])){
            $audio_data=$this->AudioModel->query_one(array('id'=>$data['audio_id']));
        }
        //查询操作人信息
        if($data['pic_id']){
            $pic=$this->ImgModel->query_one(array('id'=>$data['pic_id']));
        }
        $user=$this->AdminOpenationModel->query_sql_one("select * from t_admin_operation_log where post_id=".$data['id']." order by id desc");
        //查询分类话题
        $topic_data=$this->PostTopicModel->get_post_topic($data['id']);
        $tag_data=$this->PostTagModel->get_post_tag($data['id']);
        $data['audio_address']=$audio_data['audio_address'];
        $data['topic_data']=$topic_data;
        $data['tag_data']=$tag_data;
        $data['post_img']=$pic;
        $data['user']['nickname']=$user['nickname'];
        $data['user']['openation_time']=$user['add_time'];
        $data['user']['desc']=$user['desc'];
        $data['author']=$this->UserModel->getUserInfo($data['uid']);
        return $data;
    }


    /**
     * 获取帖子列表
     * name: getPostAll
     * @param string $status
     * @param string $uid
     * @param string $topic
     * @param string $tag
     * @param int $page
     * @param int $pagesize
     * @return array
     * @throws Exception
     * @Author:taiyang
     */
    public function getPostAll($data=array(),$page=1,$pagesize=10,$order=5){
        $sql="select p.* from ".$this->table." p ";
        $sql.=$this->getPostSql($data);
        $sql.=" group by p.id ";
        $index = $page - 1 < 0 ? 0 : ($page - 1) * $pagesize;
        $sql.=$this->getOrder($order);
//        $sql.=" order by p.add_time asc ";
        $sql.=" limit ".$index.",".$pagesize."";
//        echo $sql;
        $list=$this->query_sql_list($sql);

        return $list;
    }
    /**
     * 获取排序
     * name: getOrder
     * @param $order
     * @return string
     * @Author:taiyang
     */
    public function getOrder($order=5){
        $sql='';
        if($order==9){return $sql;}
        //todo 最新回复时间未定
        $order_arr=array(
//            1=>array('name'=>'最新回复时间','field'=>'p.update_time desc'),
            2=>array('name'=>'最多回帖量','field'=>'p.comment_num desc'),
            3=>array('name'=>'最多点赞量','field'=>'p.like_num desc'),
            4=>array('name'=>'最多观看量','field'=>'p.show_num desc'),
            5=>array('name'=>'最新发帖时间','field'=>'p.add_time desc'),
            6=>array('name'=>'最早发帖时间','field'=>'p.add_time asc'),
            7=>array('name'=>'最大爆光量','field'=>'p.show_num desc'),
            8=>array('name'=>'最近更新时间','field'=>'p.update_time desc'),
            9=>array('name'=>'最早更新时间','field'=>'p.update_time asc'),
        );
        $sql.=" order by ".$order_arr[$order]['field']." ";
        return $sql;
    }

    /**
     * 获取帖子列表的数量
     * name: getPostAllNum
     * @param string $status
     * @param string $uid
     * @param string $topic
     * @param string $tag
     * @return int
     * @throws Exception
     * @Author:taiyang
     */
    public function getPostAllNum($data=array()){
        $sql="select count(*) as count_num from (select p.* from ".$this->table." p ";
        $sql.=$this->getPostSql($data);
        $sql.=" group by p.id) t";
        return $this->query_sql_count($sql);
    }

    public function getPostSql($data=array()){
        $sql='';
        //连接操作表
        if(!empty($data['uid'])){
            $sql.=" right join t_admin_operation_log taol on p.id=taol.post_id and taol.uid=".$data['uid']." and taol.type in(1,2,3,6,8) ";
        }
        //连接话题表
        if(!empty($data['topic']) || !empty($data['s_topic'])){
            $sql.=$this->getSqlTopic($data);
        }
        //连接标签表
        if(!empty($data['tag'])){
            $sql.=" right join t_post_tag tag on tag.post_id=p.id and tag.tag_id=".$data['tag']." and tag.status=1 ";
        }
        if(!empty($data['img_w']) || !empty($data['img_h']) || !empty($data['img_size'])){
            $sql.=" left join t_img ti on ti.related_id=p.id and ti.type=1 ";
        }
        //连接user表
        if ($data['s_type_id'] == 4){
            $sql.=" right join t_user u on u.uid = p.uid ";
        }
        $sql.=" where 1 and p.id<>'' ";
        if(!empty($data['status'])){
                $sql.=" and p.status = ".$data['status']." ";
        }
        if(!empty($data['is_audit'])){
                $sql.=" and p.is_audit = ".($data['is_audit']-1)." ";
        }
        //id类型查询
        if(!empty($data['s_content'])){
            $sql.=$this->getSqlLike($data);
        }
        if($data['is_pic'] == 1){
            $sql.=" and p.pic_id!=0";
        }
        if($data['is_pic'] == 2){
            $sql.=" and p.pic_id=0";
        }
        if($data['is_hot'] == 1){
            $sql.=" and p.is_hot=1";
        }
        if($data['is_hot'] == 2){
            $sql.=" and p.is_hot=0";
        }
        if(!empty($data['use_time_s']) || !empty($data['use_time_e'])){//操作时间
            $sql.=$this->getSqlUp($data['use_time_s'],$data['use_time_e'],"p.update_time");
        }
        if(!empty($data['add_time_s']) || !empty($data['add_time_e'])){//添加时间
            $sql.=$this->getSqlAdd($data['add_time_s'],$data['add_time_e'],"p.add_time");
        }
        //通过指定类型查询
        if(!empty($data['post_type'])){
            $sql.=$this->getSqlType($data);
        }
        //查询是否带有节日词
        if(!empty($data['festival'])){
            $sql.=$this->getSqlFestival($data);
        }
        //图片大小筛选
        if(!empty($data['img_w']) || !empty($data['img_h']) || !empty($data['img_size'])) {
            $sql.=$this->getSqlImg($data);
        }
        if(!empty($data['not_in'])){
            $sql.=" and p.id not in(".$data['not_in'].") ";
        }
        return $sql;
    }

    public function getSqlImg($data=array()){
        $sql='';
        $sql.=$this->getWhereImg($data['img_w'],'w');
        $sql.=$this->getWhereImg($data['img_h'],'h');
        $sql.=$this->getWhereImg($data['img_size'],'size');
        return $sql;
    }

    public function getWhereImg($data='',$filed=''){
        $sql='';
        if(empty($data) || empty($filed)){
            return $sql;
        }
        $img_w=explode('-',$data);
        if($filed=='size'){
            $img_w[0]=$img_w[0]*1024;
            $img_w[1]=$img_w[1]*1024;
        }
        if($img_w[0]<1 && $img_w[1]>0){//0-100  取出所有小于100的
            $sql.=' and ti.'.$filed.'<'.$img_w[1].' ';
        }
        if($img_w[0]>0 && $img_w[1]>0){//100-220  取出所有大于100的小于220
            $sql.=' and ti.'.$filed.'<'.($img_w[1]>$img_w[0]?$img_w[1]:$img_w[0]).' ';//大
            $sql.=' and ti.'.$filed.'>'.($img_w[1]>$img_w[0]?$img_w[0]:$img_w[1]).' ';//小
        }
        if($img_w[0]>0 && $img_w[1]<1){//100-0  取出所有大于100的
            $sql.=' and ti.'.$filed.'>'.$img_w[0].' ';
        }
        return $sql;
    }

    /**
     * 过滤节日
     * name: getSqlFestival
     * @param array $data
     * @return string
     * @Author:taiyang
     */
    public function getSqlFestival($data=array()){
        $sql='';
        if(!empty($data['festival'])) {
            $festival_arr=array(
                '元旦', '腊八节', '大寒', '小年', '麻风节', '大年', '除夕', '新春', '春节', '海关日', '湿地日', '立春', '声援南非日', '气象节', '元宵节', '情人节', '雨水', '青年日', '龙抬头', '抗癌症日', '母语日', '罕见病日', '海豹日', '爱耳日', '惊蛰', '学雷锋纪念日', '妇女节', '植树节', '白色情人节', '消费者权益日', '国际航海日', '春分', '睡眠日', '水日', '气象日', '尊严尊敬日', '警察日', '森林日', '受难日', '愚人节', '寒食节', '清明节', '卫生日', '谷雨', '地球日', '复活节', '劳动节', '五一', '青年节', '母亲节', '小满', '端午节', '儿童节', '六一', '芒种', '父亲节', '纪念日', '香港回归', '建党节', '七夕', '建军节', '八一', '立秋', '中元节', '教师节', '中秋', '国庆', '重阳', '光棍节', '感恩节', '万圣', '立冬', '冬至', '平安夜', '双十一', '毛泽东诞辰日',
            );
            $sql.=" and ((p.title like '%双十二%' or p.desc like '%双十二%') ";
//            $sql.=" or (p.title like '%月%日%' or p.desc like '%月%日%') ";
//            $sql.=" or (p.title like '%月%初%' or p.desc like '%月%初%') ";

            foreach ($festival_arr as $str){
                $sql.=" or (p.title like '%".$str."%' or p.desc like '%".$str."%') ";
            }
            $sql.=") ";
        }
        return $sql;
    }
    /**
     * 通过分类话题查询
     * name: getSqlTopic
     * @param array $data
     * @return string
     * @Author:taiyang
     */
    public function getSqlTopic($data=array()){
        $sql='';
        if(!empty($data['s_topic'])){
            $sql.=" right join t_post_topic topic on topic.post_id=p.id and topic.topic_id in(select id from t_topic where parent_id=".$data['s_topic'].") and topic.status=1 ";
        }elseif(!empty($data['topic'])){
            $sql.=" right join t_post_topic topic on topic.post_id=p.id and topic.topic_id = ".$data['topic']." and topic.status=1 ";
        }
        return $sql;
    }
    /**
     * 通过指定类型查询
     * name: getSqlType
     * @param array $data
     * @return string
     * @Author:taiyang
     */
    public function getSqlType($data=array()){
        $sql='';
        if($data['post_type'] == 3){//用户上传
            $sql.=" and p.type=0 ";
        }else{//麻花导入
            $sql.=" and p.type=2 and p.source = '".$data['post_type']."' ";
        }
        return $sql;
    }
    /**
     * 通过指定类型和字段查询条件
     * name: getSqlLike
     * @param $data
     * @return string
     * @Author:taiyang
     */
    public function getSqlLike($data=array()){
        $sql='';
        if($data['s_type_id'] == 1){//帖子id
            $sql.=" and p.id in(".$data['s_content'].") ";
        }elseif ($data['s_type_id'] == 2){//用户uid
            $sql.=" and p.uid= '".$data['s_content']."' ";
        }elseif ($data['s_type_id'] == 3){//帖子标题
            $sql.=" and p.title like '%".$data['s_content']."%' ";
        }elseif ($data['s_type_id'] == 4){//用户昵称
            $sql.=" and u.nickname like '%".$data['s_content']."%' ";
        }
        return $sql;
    }

    /**
     * 时间格式查询
     * name: getSqlUp
     * @param string $start
     * @param string $end
     * @param string $field
     * @return string
     * @Author:taiyang
     */
    public function getSqlUp($start='',$end='',$field=''){
//        echo '----'.$start.'---'.$end;
        $sql='';
        if(!empty($start)&&!empty($end)){
            $start=$start." 00:00:00";
            $end=$end." 00:00:00";
            $end=date('Y-m-d',strtotime($end)+86400)." 00:00:00";
            $sql.=" and (".$field." BETWEEN '".$start."' and '".$end."') ";
        }else{
            if(!empty($start)){
                $start.=" 00:00:00";
                $end=date('Y-m-d',strtotime($start)+86400)." 00:00:00";
                $sql.=" and (".$field." BETWEEN '".$start."' and '".$end."') ";
            }else{
                if(!empty($end)){
                    $end=$end." 00:00:00";
                    $start=date('Y-m-d',strtotime($end)+86400)." 00:00:00";
                    $sql.=" and (".$field." BETWEEN '".$end."' and '".$start."') ";
                }
            }
        }
        return $sql;
    }

    /**
     * 时间戳格式查询
     * name: getSqlAdd
     * @param string $start
     * @param string $end
     * @param string $field
     * @return string
     * @Author:taiyang
     */
    public function getSqlAdd($start='',$end='',$field=''){
        $sql='';
        if(!empty($start)){
            $start=strtotime($start);
        }
        if(!empty($end)){
            $end=strtotime($end);
        }
        if(!empty($start)&&!empty($end)){
            $end=$end+86400;
            $sql.=" and (".$field." BETWEEN '".$start."' and '".$end."') ";
        }else{
            if(!empty($start)){
                $end=$start+86400;
                $sql.=" and (".$field." BETWEEN '".$start."' and '".$end."') ";
            }else{
                if(!empty($end)){
                    $start=$end+86400;
                    $sql.=" and (".$field." BETWEEN '".$end."' and '".$start."') ";
                }
            }
        }
        return $sql;
    }

    /**
     * 删除一个帖子
     * name: del_post
     * @param string $post_id  帖子id
     * @return bool
     * @throws Exception
     * @Author:taiyang
     */
    public function del_post($post_id=''){
        $res=$this->PostModel->update_data(array('status'=>3,'is_audit'=>1),array('id'=>$post_id));
        if($res !== false){
            //查询帖子的uid
            $post=$this->PostModel->query_one(array('id'=>$post_id));
            // 修改用户统计   帖子数-1
            $this->UserCount->db->set('pub_num','pub_num-1',false)->where(array('uid'=>$post['uid']));
            $this->UserCount->db->update('t_user_count');
        }
        //查询分类话题
        $topic_id=$this->PostTopicModel->get_post_topic($post_id);
        $tag_id=$this->PostTagModel->get_post_tag($post_id);
        //移除话题
        if($topic_id['ids']){
            foreach ($topic_id['ids'] as $t_id){
                $this->PostTopicModel->del_add_post_topic($post_id,$t_id,2);
            }
        }
        //移除标签
        if($tag_id['ids']){
            foreach ($tag_id['ids'] as $t_id){
                $this->PostTagModel->del_add_post_tag($post_id,$t_id,2);
            }
        }
        //task-event
        //触发任务埋点
        $this->taskEventApi('del_post',array('uid'=>$post['uid'],'data'=>'del_post:'.$post_id));
        return true;
    }


    /**
     * 取出所有来源
     * name: get_source
     * @return array
     * @throws Exception
     * @Author:taiyang
     */
    public function get_source(){
        $sql="SELECT DISTINCT source FROM t_post WHERE 1 AND source <> ''";
        return $this->query_sql_list($sql);
    }


}